const { User, Subscribe } = require("../model");
const { createToken, verifyToken } = require("../utils/jwt");
const mongoose = require("mongoose");

const userController = {};

//根据id获取用户信息
// userController.getUser = async ctx => {
//   const id = ctx.params.id
//   const data = await User.findById(id)
//   ctx.body = {code:200,data,msg:'成功'}
// };

//用户注册
userController.register = async (ctx) => {
  const dbBack = await new User(ctx.request.body).save();
  console.log(dbBack, "== dbBack ==");
  ctx.body = { code: 200, msg: "用户注册成功", data: dbBack };
};

//用户登录
userController.login = async (ctx) => {
  const dbBack = await User.findOne(ctx.request.body);
  if (dbBack) {
    //返回token
    const token = await createToken({ dbBack });
    let newData = { ...dbBack._doc, token };
    ctx.body = { code: 200, data: newData, msg: "登录成功" };
  } else {
    ctx.body = { code: 200, msg: "用户名或者密码错误!" };
  }
};

// 获取用户信息(包含关注和被关注的状态)
// 1.创建一个新的关注和被关注的表
// 2.定义好user和channel(被关注的用户id)
// 3.如果是登录状态的查询一下是否已经关注并且将这个状态保存下来添加到用户信息
userController.getUser = async (ctx) => {
  const userId = ctx.params.userId; //获取目标用户(频道)的id
  console.log(ctx.user, "=== ctx.user 38 ===");
  const loginUserId = ctx.user ? ctx.user.userInfo._id : null; //如果存在登录的用户则顺便查询一下登录用户是否关注了目标用户(频道)
  let isSubscribe = false;
  if (loginUserId) {
    //
    const isExitUser = await Subscribe.findOne({
      user: loginUserId,
      channel: userId,
    });
    if (isExitUser) {
      isSubscribe = true;
    }
  }
  //查询目标用户(频道)相关数据并返回
  const isValidId = mongoose.Types.ObjectId.isValid(userId);
  if (!isValidId) {
    ctx.throw(400, "id不是符合的ObjectId...");
    return;
  }
  const userInfo = await User.findById(userId, [
    "email",
    "username",
    "image",
    "cover",
    "channeldes",
  ]);
  if (userInfo) {
    let resObj = { ...userInfo._doc, isSubscribe };
    ctx.body = { code: 200, msg: "获取用户信息成功", data: resObj };
  } else {
    ctx.throw(400, "查询不到相关用户信息");
  }
};

//关注用户并返回相关关注信息
userController.subscribe = async (ctx) => {
  console.log(ctx, "=== cuser76 ===");
  const subscribeId = ctx.params.subscribeId;
  const loginUserId = ctx.user.dbBack._id;
  if (subscribeId == loginUserId) {
    return ctx.throw(400, "不能关注自己!");
  }
  //查询是否已经关注了
  const dbBack = await Subscribe.findOne({
    user: loginUserId,
    channel: subscribeId,
  });
  if (dbBack) {
    return ctx.throw(400, "已经关注过了!");
  } else {
    const isSubscribe = await new Subscribe({
      user: loginUserId,
      channel: subscribeId,
    }).save();
    if (isSubscribe) {
      const subUserInfo = await User.findById(subscribeId, [
        "username",
        "email",
        "phone",
        "image",
        "channeldes",
        "subscribeCount",
      ]);
      subUserInfo.subscribeCount++;
      await subUserInfo.save();
      ctx.body = { code: 200, msg: "关注成功", data: subUserInfo };
    } else {
      ctx.throw(500, "关注失败，服务器出问题");
    }
  }
};

//关注列表
userController.subscribeList = async (ctx) => {
  const loginUserId = ctx.user.dbBack._id;
  const subscribeList = await Subscribe.find({ user: loginUserId }).populate(
    "channel",
    ["username", "email", "phone", "image", "channeldes", "subscribeCount"]
  );
  ctx.body = subscribeList
};

module.exports = userController;
